

INVESTIGATIONTITLE = "lflj134"
ADMINURL  = "https://icat.admin.ws.host.net/ICATAdminService/ICATAdmin"
ICATURL  = "https://icat.ws.host.net/ICATService/ICAT"
ICATUSER = "user"
ICATPASS = "pass"
ADMINUSER ="admin" 
ADMINPASS ="pass"

from icatWS.ICATAdminService_client import *
from icatWS.ICATService_client import *
from icatWS.ICATService_types import ns0
from ZSI import FaultException
import sys

#login to admin
loc = ICATAdminServiceLocator()
kw = {  #  'tracefile' : sys.stdout,
        'user': ADMINUSER, 'password':ADMINPASS,
        'auth' : ( ZSI.client.AUTH.httpbasic,  ADMINUSER, ADMINPASS ) }
adminBinding = loc.getICATAdminPort(ADMINURL, **kw) # returns SOAP object
#
request = loginAdmin()
request._username = ICATUSER
response = adminBinding.loginAdmin(request)
adminSessionId = response._return
print adminSessionId


#login to icat
loc = ICATServiceLocator()
kw = {  #  'tracefile' : sys.stdout,
        'user': ICATUSER, 'password':ICATPASS,
        'url': ICATURL,
        'auth' : ( ZSI.client.AUTH.httpbasic,  ICATUSER, ICATPASS) }
#
icatBinding = loc.getICATPort(**kw) # returns SOAP object
request = login()
request._username = ICATUSER
request._password = ICATPASS
response = icatBinding.login(request)
sessionId = response._return 
print sessionId

#list instruments
request = listInstruments()
request._sessionId = sessionId
response = icatBinding.listInstruments(request)
print response._return

#list dataset types
request = listDatasetTypes()
request._sessionId = sessionId
response = icatBinding.listDatasetTypes(request)
print response._return


#list investigation types
request = listInvestigationTypes()
request._sessionId = sessionId
response = icatBinding.listInvestigationTypes(request)
print response._return


#list listDatasetStatus
request = listDatasetStatus()
request._sessionId = sessionId
response = icatBinding.listDatasetStatus(request)
print response._return


print "Retrieving ICAT investigation data for ", INVESTIGATIONTITLE
advSearchDetails= ns0.advancedSearchDetails_Def("dummy")
advSearchDetails._caseSensitive=True
advSearchDetails._investigationName = INVESTIGATIONTITLE
advSearchDetails._investigationInclude = "DATASETS_ONLY"

request = searchByAdvanced()
request._sessionId = sessionId
request._advancedSearchDetails = advSearchDetails
try:
    response = icatBinding.searchByAdvanced(request)
    invHolderList = response._return
except:
    import sys
    print "Unexpected error:", sys.exc_info()[0]
    # possibly the sessionId has timed out. it had an hour
    # but this could be slow ...
    # maybe we could respawn the connection?
    sys.exit(1)

  # did we get a match? If not, then its a new investigation ...
if invHolderList:

    print "Need to update records for ",INVESTIGATIONTITLE, " .........."
    print type(invHolderList)
    invHolder = invHolderList[0]
    print "facility = ",invHolder.Facility
    print vars(invHolder)
    datasets = invHolder.DatasetCollection

    print "datasets: " , len(datasets)
    for dataset in datasets:
        print dataset._id, dataset._name, dataset._datasetType
        if not hasattr(dataset, "_datafileCollection"): continue
        datafiles = dataset._datafileCollection
        print "datafiles " , len(datafiles)
        print ""
        if len(datafiles)<=0: continue
        datafile0 = datafiles[0]
        print "  " , datafile0._name, datafile0._datafileVersion
        print "  " , vars(datafile0._datafileFormat._datafileFormatPK)
        print "  " , datafile0._datafileModifyTime

else:
    print "No prior records for ",INVESTIGATIONTITLE, "in ICAT!"


# retrieve specific, basic
#invs = icatcnx.getMyInvestigations(sessionId)
#print invs
#invHolder =  icatcnx.getInvestigation(sessionId,5700)

# try to generate a new user in facility users table
user= ns0.facilityUser_Def("dummy")
# required entity base bean fields ...  # WTF????
user._facilityAcquiredData = True   
#user._icatRole =  "?" 
user._selected = False  
user._uniqueId =  "new_dummy_user"
# investigator extensions ...
user.facilityUserId = "new_dummy_user"
user.federalId = "new_dummy_user"
user.firstName =  "New"
user.initials =  "N D"
user.lastName =  "User"
user.middleName =  "Dummy"
user.title =  "Mr"

investPK = ns0.investigatorPK_Def("dummy")
# required primaryKey base bean fields ... 
# investPK extensions
investPK.facilityUserId = "new_dummy_user"
investPK.investigationId =  1

invest = ns0.investigator_Def("dummy")
# required entity base bean fields ... 
invest._facilityAcquiredData = True    # WTF????
#invest._icatRole =  "?" 
invest._selected = False  
invest._uniqueId =  "thisUniqueId"
# investigator extensions ...
invest._facilityUser =  user
invest._investigatorPK  = investPK
invest._role  =  "INVESTIGATOR"

request = addInvestigator()
request._sessionId = sessionId
request._investigator = invest
request._investigationdId = 1 
print "adding new user..."
response =  icatBinding.addInvestigator(request)
print "added new user? ", response._return



request = logout()
request._sessionId = sessionId
response = icatBinding.logout(request)
print "logged out: ", response._return

# no admin logout function
